package com.ajie.config;

import cn.dev33.satoken.session.SaSession;
import cn.dev33.satoken.session.SaSessionCustomUtil;
import cn.dev33.satoken.stp.StpInterface;
import cn.dev33.satoken.stp.StpUtil;
import com.ajie.service.SysUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: ajie
 * @createTime: 2024-06-23 11:54
 */
@Component
public class StpInterfaceImpl implements StpInterface {

    @Resource
    private SysUserService userService;

    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        List<String> permissionList = new ArrayList<>();
        // 迭代角色列表 - 根据角色code获取权限code
        for (String roleCode : getRoleList(loginId, loginType)) {
            SaSession session = SaSessionCustomUtil.getSessionById("role-" + roleCode);
            List<String> permissions = session.get("Permission_List", () -> userService.listPermissionByRoleCode(roleCode));
            permissionList.addAll(permissions);
        }
        return permissionList;
    }

    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        SaSession saSession = StpUtil.getSessionByLoginId(loginId);
        return saSession.get("Role_List", () -> userService.listRoleByUserId(loginId.toString()));
    }
}
